<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="css/bootstrap.min.css" />
    <link rel="stylesheet" href="css/font-awesome.css" />
    <script src="js/vue.js"></script>
    <script src="js/vendor/jquery-1.12.4.min.js"></script>
    <script src="js/bootstrap.min.js"></script>
    <script src="js/jquery.cookie.min.js"></script>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }
    body {
        background-color: #EEEEEE;
    }
    .navbar-text a  {
        color: #ffffff;
    }
    .login-text {
        margin-right: 50px;
    }
    .logo {
        color: #E94F4C;
        font-size: 35px;
        display: inline-block;
    }
    .search-box {
        height: 48px;
    }
    .input-group-addon {
        background-color:#E94F4C;
        border: none;
        color: #ffffff;
    }
    .control-icon {
        position: absolute;
        top: 50%;
    }
    .mgt38 {
        margin-top: 30px;
    }
    .thumbnail a img {
        height: 200px;
        width: 200px;
    }
    .thumbnail .description {
        height: 40px;
        overflow: hidden;
    }
    a:hover {
        text-decoration: none;
    }
    h3, p {
        text-align: center;
    }
    table tr {
        background-color: #ffffff;
    }
</style>
<body>
    <nav class="navbar navbar-default navbar-inverse navbar-static-top">
        <div class="container-fluid">
            <div class="navbar-header">
                <a href="前端首页.html" class="navbar-brand" style="color: #ffffff;"><i class="fa fa-sign-language"></i> 寻欢易购</a>
            </div>
            <p class="navbar-text navbar-right login-text">
                <a id="loginText" href="登录页面.html">登录</a>
            </p>
            <p class="navbar-text navbar-right">
                <a href="仿京东注册.html">注册</a>
            </p>
        </div>
    </nav>
    <div class="container-fluid">
        <div class="row">
            <div class="col-xs-8 col-xs-push-2">
                <table id="app" class="table">
                    <thead>
                        <tr>
                            <td>商品</td>
                            <td>单价</td>
                            <td>数量</td>
                            <td>小计</td>
                            <td>操作</td>
                        </tr>
                    </thead>
                    <tbody >
                        <tr v-for="g in goods">
                            <td style="max-width: 200px;">
                                <div class="media">
                                    <div class="media-left">
                                        <a href="javascript: void(0);">
                                            <img class="media-object" height="80px" width="62px" :src="g.smallPic">
                                        </a>
                                    </div>
                                    <div class="media-body">
                                        <h4 class="media-heading">{{g.title}}</h4>
                                    </div>
                                </div>
                            </td>
                            <td>{{g.price}}</td>
                            <td>
                                <div class="input-group" style="width: 120px;">
                                    <!-- v-if 如果成立就显示该dom元素 -->
                                    <span v-if="g.num == 1" style="background-color: #e2e2e2;"
                                          class="input-group-addon">-</span>
                                    <!-- v-else必须和v-if放在一起 -->
                                    <span :gid="g.goodsId" onclick="reduceGoodNum(this)" v-else class="input-group-addon"
                                          style="cursor: pointer;">-</span>
                                    <input class="form-control" v-model="g.num">
                                    <span :gid="g.goodsId" class="input-group-addon" onclick="addGoodNum(this)"
                                          style="cursor: pointer;">+</span>
                                </div>
                            </td>
                            <td>{{g.price * g.num}}</td>
                            <td>
                                <button :id="g.goodsId" onclick="deleteSpecifyGood(this)" class="btn btn-default">删除</button>
                            </td>
                        </tr>
                    </tbody>
                    <tfoot>
                        <tr v-if="goods.length != 0">
                            <td colspan="5">
                                已选购 <span id="totalCount" style="color: red;">{{totalNum}}</span> 件商品,
                                总价 <span style="color: red;" id="totalPrice">{{totalPrice}}</span>
                                <button onclick="gotoSettleCount()" class="btn btn-danger btn-lg">去结算</button>
                            </td>
                        </tr>
<!--                        <tr>-->
<!--                            <td colspan="5">暂无商品.<a href="前端首页.html">去购物</a></td>-->
<!--                        </tr>-->

                    </tfoot>
                </table>
            </div>
        </div>
    </div>
</body>
    <script>
        var vm = new Vue({
            el: '#app',
            data: {
                goods: [],
                totalNum: 0,
                totalPrice: 0
            },
            code: 0
        });

        var vm2 = new Vue({
            el: '#dropdown',
            data: {
                username: null
            },
        });

        //登录验证
        $(function () {
            $.ajax({
                url: 'http://localhost:8080/loginJudge',
                type: 'get',
                dataType: 'json',
                data: {
                    method: "login"
                },
                success: function (_data) {
                    // 如果用户登录
                    code = _data.code;
                    vm2.username = _data.username;
                    if (code == 2) {
                        $('#login').css('display', 'none');
                        $('#dropdown').css('display', 'block')
                    }
                }
            })
        });

        //退出登录
        function quit() {
            $.ajax({
                url: 'http://localhost:8080/loginJudge',
                type: 'get',
                dataType: 'json',
                data: {method: "quit"}
            });
            localStorage.removeItem('local_shopping_cart');
            location.reload();
        }

        //购物车数据初始化
        var localShoppingCart = localStorage.getItem('local_shopping_cart');


        //判断本地购物车是否有数据
        if (localShoppingCart) {
            //本地数据转换为json数据
            localShoppingCart = JSON.parse(localShoppingCart);
            //取得商品id的数组
            var goodIds = Object.keys(localShoppingCart);
            // join(‘,’) 只用指定的字符将数组拼接成字符串
            var goodIdsStr = goodIds.join(','); // ['1001', '1002', '1003'] -> 1001,1002,1003
            //用商品id获取商品信息
            $.ajax({
                url: 'http://localhost:8080/selectById/'+goodIdsStr,
                type: 'post',
                dataType: 'json',
                success: function (_data) {  // [{}, {}, {}]
                    var totalNum = 0;  //总数量
                    var totalPrice = 0;//总价格
                    for (var i = 0; i < _data.length; i++) {
                        var good = _data[i];  //获取到每件商品
                        var goodId = good.goodsId; //获取商品的id, 目的是获取商品的数量
                        // 动态的添加的属性, 购买的商品数量
                        good.num = localShoppingCart['' + goodId];

                        totalNum += good.num;   //计算总数量
                        totalPrice += (good.num * good.price); //计算总的价格
                        vm.goods.push(good);
                    }
                    vm.totalNum = totalNum;
                    vm.totalPrice = totalPrice;
                }
            })
        }


        //购物车商品的数量减1
        function reduceGoodNum(reduceTag) {
            //获取id
            var goodId = $(reduceTag).attr('gid');
            //获取本地购物车所有的商品数据
            var localShoppingCart = JSON.parse(localStorage.getItem('local_shopping_cart'));
            //获取指定id的商品的数量，并--
            var num = --localShoppingCart[goodId];
            //给对应的商品的数量重新赋值
            localShoppingCart[goodId] = num;
            // 改变商品的数量：1.登录；2.未登录
            changeChartNum(goodId, num, localShoppingCart);
        }

        //购物车商品的数量加1
        function addGoodNum(addTag) {
            //获取id
            var goodId = $(addTag).attr('gid');  //goodId 是String类型
            // 获取本地购物车的数据
            var localShoppingCart = JSON.parse(localStorage.getItem('local_shopping_cart'));
            //获取指定id的商品的数量，并++
            var num = ++localShoppingCart[goodId];
            //给对应的商品的数量重新赋值
            localShoppingCart[goodId] = num;
            // 改变商品的数量：1.登录；2.未登录
            changeChartNum(goodId, num, localShoppingCart);
        }

        // 改变购物车对应的商品的数量， 分为远程和本地
        function changeChartNum(goodId, num, lsc) {
            // 表示用户登录了, 需要去同步远程服务器端的数据
            if (code == 2) {
                $.ajax({
                    url: 'http://localhost:8080/updateCart/'+goodId+num,
                    type: 'post',
                    dataType: 'json',
                    data: {goodId: goodId, num: num},
                })
                localStorage.setItem('local_shopping_cart', JSON.stringify(lsc));
                reRenderCart(goodId, num)
            } else {  // 如果用户没有登录，只用同步本地就行了
                localStorage.setItem('local_shopping_cart', JSON.stringify(lsc));
                reRenderCart(goodId, num)
            }
        }

        //加、减后渲染购物车数据
        function reRenderCart(goodId, num) {
            //取出所有的商品
            var goodList = vm.goods;
            //字符串转数字
            goodId = Number(goodId);
            //定义商品的总数量和总价格
            var totalNum = 0;  //总数量
            var totalPrice = 0;//总价格
            //遍历vue里的所有商品
            for (var i = 0; i < goodList.length; i++) {
                var good = goodList[i];
                //修改对应的商品数量
                if (good.goodsId == goodId) {
                    good.num = num;
                }
                totalNum += good.num;
                totalPrice += (good.num * good.price);
            }
            //本地总数变化
            vm.totalNum = totalNum;
            vm.totalPrice = totalPrice;
        }


        function deleteSpecifyGood(delbtnTag) {
            //获取商品ID
            var goodId = $(delbtnTag).prop('id');
            console.log(goodId)
            //字符串转json
            var localShoppingCart = JSON.parse(localStorage.getItem('local_shopping_cart'));
            // 如果用户登录, 需要删除服务器端购物车中对应的商品
            if (code == 2) {
                removeServerCartData(goodId);
            }
            //删除本地对应的商品
            delete localShoppingCart[goodId];

            var totalNum = 0;  // 商品的总数量
            var totalPrice = 0;  // 总价格

            //表示清空了
            if (Object.keys(localShoppingCart).length == 0) {
                // 将存储购物车的信息删掉
                localStorage.removeItem('local_shopping_cart');
                vm.totalNum = 0;
                vm.totalPrice = 0;
                vm.goods = [];
                return;
            }
            //更新本地购物车数据
            localStorage.setItem('local_shopping_cart', JSON.stringify(localShoppingCart));

            var goodList = vm.goods;  //取出所有的商品
            goodId = Number(goodId); // 将字符串转换为数字类型
            //遍历本地所有商品
            for (var i = 0; i < goodList.length; i++) {
                var good = goodList[i];
                if (goodId == good.goodId) {
                    goodList.splice(i, 1);  // 删除指定的商品
                    i--;
                } else {  //没有删除的商品要纳入计算
                    totalNum += good.num;
                    totalPrice += (good.num * good.price);
                }
            }
            vm.totalNum = totalNum;
            vm.totalPrice = totalPrice;
        }

        // 删除掉远程服务器端对应的购物车数据
        function removeServerCartData(goodId) {
            $.ajax({
                url: 'http://localhost:8080/delect/'+goodId,
                type: 'post',
                dataType: 'json',
            })
        }

        // 点击 "结算" 按钮，到达结算页面
        function gotoSettleCount() {
            //验证登陆
            $.ajax({
                url:'http://localhost:8080/loginJudge',
                data:{method:'login'},
                type:'get',
                datatype:'json',
                success:function (_data) {
                    if (_data.code==2) {
                        window.location.href = "shop_end.html"
                    }else if (_data.code==1) {
                        window.location.href = "login.html"
                    }

                }
            })

        }

        // 显示错误提示信息
        function showErrorBox(msgText) {
            Lobibox.notify('warning', {
                size: 'mini',
                delay: 2000,
                delayIndicator: false,
                title: false, //不给title
                msg: msgText,
                sound: false  // 不要音频
            })
        }
    </script>
</html>